//
//  ContactViewController.m
//  QQ_Youngsher
//
//  Created by Maxwell on 16/1/14.
//  Copyright © 2016年 LLLTeam. All rights reserved.
//

#import "ContactViewController.h"
#import "Group.h"
#import "Friend.h"
#import "ResultData.h"
#import "DetailTableViewCell.h"
#import <MJRefresh.h>
#import <AFNetworking.h>
#import <AFNetworkReachabilityManager.h>
#import <UIImageView+WebCache.h>

#define SCREEN_W [[UIScreen mainScreen] bounds].size.width
#define SCREEN_H [[UIScreen mainScreen] bounds].size.height

static NSString *const dataURL = @"http://f.wallstcn.com/news.json";

@interface ContactViewController ()
@property (nonatomic ,strong)UITableView *contactTableView;
@property (nonatomic ,strong)Headview *contactHeadView;
@property (nonatomic ,strong)NSMutableArray *groupArray;//分组数组
@property (nonatomic ,strong)NSMutableArray *dataSourceArray;//联系人数组
@property (nonatomic ,strong)NSMutableArray *tempDataSourceArray;//用于展示数据的中间数组

@end

@implementation ContactViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = @"联系人";
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"contact_y"] style:(UIBarButtonItemStylePlain) target:self action:@selector(personalSetting:)];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"添加" style:(UIBarButtonItemStylePlain) target:self action:@selector(add:)];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    
    [self requestContactData];
    [self initArray];
    [self initContactHeadView];
    [self initContactTableView];
    
//    下拉刷新
    __weak typeof(self) weakself =  self;
    self.contactTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        __strong typeof(weakself) strongself = weakself;
        if (strongself) {
            [self requestContactData];
        }
        
    }];
    
}
- (void)initArray{
    _groupArray = [[NSMutableArray alloc] init];
    _dataSourceArray = [[NSMutableArray alloc] init];
    _tempDataSourceArray = [[NSMutableArray alloc] init];
}

- (void)personalSetting:(UIBarButtonItem *)item{
    NSLog(@" %d | %s | %@",__LINE__,__FUNCTION__,item);
}
- (void)add:(UIBarButtonItem *)item{
    NSLog(@" %d | %s | %@",__LINE__,__FUNCTION__,item);
    
}
- (void)initContactHeadView{
    NSMutableArray *imageArray = [NSMutableArray arrayWithObjects:@"new",@"special",@"group", @"public", nil];
    NSMutableArray *titleArray = [NSMutableArray arrayWithObjects:@"新朋友",@"特别关心",@"群组",@"公众号", nil];
    _contactHeadView = [[Headview alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 130) imageArray:imageArray titleArray:titleArray];
    _contactHeadView.delegate = self;
}

- (void)initContactTableView{
    _contactTableView = [[UITableView alloc] initWithFrame:[[UIScreen mainScreen] bounds] style:UITableViewStylePlain];
    _contactTableView.backgroundColor = [UIColor colorWithRed:0.9569 green:0.9569 blue:0.9569 alpha:1.0];
    _contactTableView.delegate = self;
    _contactTableView.dataSource = self;
    _contactTableView.tableHeaderView = _contactHeadView;
    _contactTableView.tableFooterView = [[UIView alloc] init];
    
    [self.view addSubview:_contactTableView];
}

#pragma mark - HeadViewDelegate
- (void)clickHeadViewBtn:(UIButton *)btn{
    switch (btn.tag) {
        case 0:
            NSLog(@" %d | %s | %@",__LINE__,__FUNCTION__,@"搜索");
            break;
        case 1:
            NSLog(@" %d | %s | %@",__LINE__,__FUNCTION__,@"新朋友");
            break;
        case 2:
            NSLog(@" %d | %s | %@",__LINE__,__FUNCTION__,@"特别关心");
            break;
        case 3:
            NSLog(@" %d | %s | %@",__LINE__,__FUNCTION__,@"群组");
            break;
        case 4:
            NSLog(@" %d | %s | %@",__LINE__,__FUNCTION__,@"公众号");
            break;
        default:
            break;
    }
}
#pragma mark - GroupViewDelegate
- (void)openOrCloseGroupInSection:(NSInteger)section{
    
    if ([_tempDataSourceArray[section] count] > 0) {
        NSLog(@"关闭第%ld组",(long)section);
        //关闭分组
        for (NSInteger i = [_dataSourceArray[section] count]; i > 0; i--) {
            [_contactTableView beginUpdates];
            [_tempDataSourceArray[section] removeObjectAtIndex:0];
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:section];
            [_contactTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            [_contactTableView endUpdates];
        }
        
    }else{
        NSLog(@"打开第%ld组",(long)section);
        //打开分组
        for (NSInteger i = 0; i < [_dataSourceArray[section] count]; i++) {
            [_contactTableView beginUpdates];
            [_tempDataSourceArray[section] insertObject:_dataSourceArray[section][i] atIndex:i];
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:section];
            [_contactTableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            [_contactTableView endUpdates];
        }

    }
    
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 60;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1) {
        return 20;
    }
    return 70;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    static NSString *identifire = @"group";
    UIView *view = [tableView dequeueReusableCellWithIdentifier:identifire];
    if (view == nil) {
        GroupView *gView = [[GroupView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 60)];
        gView.delegate = self;
        gView.section = section;
        gView.switchImageView.image = [UIImage imageNamed:@"contact_n"];
        ResultData *result = _groupArray[section];
        Group *group = [[Group alloc] init];
        [group setValuesForKeysWithDictionary:result.category];
        gView.titleLabel.text = group.categoryName;
        NSInteger allNumber = [_dataSourceArray[section] count];
        NSInteger onLine = 0;
        for (Friend *friend in _dataSourceArray[section]) {
            if (friend.followStatus) {
                onLine ++;
            }
            
        }
        
        gView.numberLabel.text = [NSString stringWithFormat:@"%ld/%ld", onLine,allNumber];
        if (section == 1) {
            gView.numberLabel.text = @"未匹配";
        }
        view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 60)];
        [view addSubview:gView];
    }
    return view;
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _groupArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 1) {
        return 1;
    }else{
        return [_tempDataSourceArray[section] count];
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 1) {
        UITableViewCell *cell = [[UITableViewCell alloc] init];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor colorWithRed:0.8353 green:0.8353 blue:0.8353 alpha:1.0];
        return cell;
    }else{
        static NSString *identifier = @"DetailTableViewCell";
        DetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:identifier owner:self options:nil] lastObject];
            Friend *friend = _dataSourceArray[indexPath.section][indexPath.row];
            cell.nameLabel.text = friend.nickname;
            if (friend.followStatus) {
                cell.zoneLabel.text = [NSString stringWithFormat:@"[在线]%@",friend.intro];
            }else if(!friend.followStatus){
                cell.zoneLabel.text = [NSString stringWithFormat:@"[离线]%@",friend.intro];
            }
            if (indexPath.section == 0 && indexPath.row == 1) {
                cell.zoneLabel.text = friend.intro;
            }
            [cell.headImageView sd_setImageWithURL:[NSURL URLWithString:friend.avatar] placeholderImage:[UIImage imageNamed:@"contact_y"]];
            cell.newsLabel.hidden = YES;
            cell.timeLabel.hidden = YES;
        }
        return cell;
    }
    
}

//数据请求
- (void)requestContactData{
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:dataURL parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        NSLog(@" %d | %s | %@",__LINE__,__FUNCTION__,downloadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSMutableArray *arr = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"数据请求成功");
    
        //数据请求成功
        [_dataSourceArray removeAllObjects];
        [_groupArray removeAllObjects];
        [_tempDataSourceArray removeAllObjects];
        
        
        Friend *friend00 = [[Friend alloc] init];
        friend00.nickname = @"我的电脑";
        friend00.intro = @"无需数据线，手机轻松传文件到电脑";
        friend00.followStatus = YES;
        Friend *friend01 = [[Friend alloc] init];
        friend01.nickname = @"发现新设备";
        friend01.intro = @"搜索附近的设备，用QQ轻松连接设备";
        friend01.followStatus = false;
        NSMutableArray *arr00 = [NSMutableArray arrayWithObjects:friend00,friend01, nil];
        [_dataSourceArray addObject:arr00];
        NSMutableArray *arr01 = [[NSMutableArray alloc] init];
        [_dataSourceArray addObject:arr01];
        
        ResultData *result00 = [[ResultData alloc] init];
        result00.category = @{@"categoryName":@"我的设备"};
        ResultData *result01 = [[ResultData alloc] init];
        result01.category = @{@"categoryName":@"手机通讯录"};
        [_groupArray addObject:result00];
        [_groupArray addObject:result01];
        
        
        for (NSDictionary *dic in arr) {
            ResultData *result = [[ResultData alloc] init];
            [result setValuesForKeysWithDictionary:dic];
            NSMutableArray *contactArr = [[NSMutableArray alloc] init];
            for (NSDictionary *dict in result.authors) {
                Friend *friend = [[Friend alloc] init];
                [friend setValuesForKeysWithDictionary:dict];
                [contactArr addObject:friend];
            }
            [_dataSourceArray addObject:contactArr];
            [_groupArray addObject:result];
        }
        NSLog(@"-----%ld",_groupArray.count);
        NSLog(@"+++++%ld",_dataSourceArray.count);
        
        for (int i = 0; i < _dataSourceArray.count; i++) {
            NSMutableArray *nilArr = [[NSMutableArray alloc] init];
            [_tempDataSourceArray addObject:nilArr];
        }
        
        [_contactTableView reloadData];
        [self.contactTableView.mj_header endRefreshing];
        
        //存储数据
//        NSString *filePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
//        NSString *dataPath = [filePath stringByAppendingPathComponent:@"dataArray.data"];
//        [NSKeyedArchiver archiveRootObject:arr toFile:dataPath];
        
        //读取数据
//        NSMutableArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:dataPath];
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"数据请求失败");
        [self.contactTableView.mj_header endRefreshing];
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
